package com.ztej.query.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.ztej.query.R;
import com.ztej.query.adapter.StaffAdapter;
import com.ztej.query.model.Contact;
import com.ztej.query.parser.JsonHelper;
import com.ztej.query.utils.Tools;
import com.ztej.query.views.pullableview.MyAdapter;
import com.ztej.query.views.pullableview.MyListener;
import com.ztej.query.views.pullableview.PullToRefreshLayout;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.security.AccessController.getContext;

public class StaffActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener, PullToRefreshLayout.OnRefreshListener{

//    private  Activity staffActivity;
//
//    public Activity getStaffActivity() {
//        return staffActivity;
//    }
//
//    public void setStaffActivity(Activity staffActivity) {
//        this.staffActivity = staffActivity;
//    }

    public static StaffActivity staffActivity = null;

    private static final int load = 0, pull_up = 1, pull_down = 2;

    private Button btnBack, btnFront, btnBehind;
    private CheckBox cbSearch;
    private TextView tvPage;

    private int page = 1;

    private LinearLayout llSearch;
    private TextView tvSearch;
    // 定义PopupWindow
    private PopupWindow popWindow;
    // 获取手机屏幕分辨率的类
    private DisplayMetrics dm;

    private SwipeRefreshLayout mSwipeLayout;
    private static final int REFRESH_COMPLETE = 0X110;
    private ListView lvStaff;
    private StaffAdapter mStaffAdapter;
    private List<Contact> list_staff;

    ListView listView;

    private PullToRefreshLayout pullToRefreshLayout;


//    Map<String, String> mapContact = new HashMap<String, String>();
//    List<Map<String, String>> listContact = new ArrayList<Map<String, String>>();
    List<Contact> listContact = new ArrayList<Contact>();
    private static class MyHandler extends Handler {
        private final WeakReference<StaffActivity> mActivity;

        public MyHandler(StaffActivity activity) {
            mActivity = new WeakReference<StaffActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            StaffActivity activity = mActivity.get();
            if (activity != null) {
                // ...
                switch (msg.what){
                    case REFRESH_COMPLETE:
//                    new MyAdapter().notifyDataSetChanged();
                        activity.mSwipeLayout.setRefreshing(false);
                        break;

                    case load:
                        JsonHelper jsonHelper = new JsonHelper();
                        activity.listContact = jsonHelper.parseContact((String)msg.obj);
                        if (activity.listContact!=null && activity.listContact.size()!=0){
                            activity.mStaffAdapter = new StaffAdapter(activity, activity.listContact);
                            activity.mStaffAdapter.notifyDataSetChanged();
//                            activity.lvStaff.setAdapter(activity.mStaffAdapter);
                            activity.listView.setAdapter(activity.mStaffAdapter);
                        }else {
                            Toast.makeText(activity, "暂时没有数据", Toast.LENGTH_SHORT).show();
                        }
                        break;

                    case pull_up:
                        JsonHelper jsonHelper1 = new JsonHelper();
                        activity.listContact = jsonHelper1.parseContact((String)msg.obj);
                        if (activity.listContact!=null && activity.listContact.size()!=0){
                            activity.mStaffAdapter = new StaffAdapter(activity, activity.listContact);
                            activity.mStaffAdapter.notifyDataSetChanged();
                            activity.listView.setAdapter(activity.mStaffAdapter);

                            activity.pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);

                        }else {
                            Toast.makeText(activity, "暂时没有数据", Toast.LENGTH_SHORT).show();
                            activity.pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                        }
                        break;

                    case pull_down:
                        JsonHelper jsonHelper2 = new JsonHelper();
                        activity.listContact = jsonHelper2.parseContact((String)msg.obj);
                        if (activity.listContact!=null && activity.listContact.size()!=0){
                            activity.mStaffAdapter = new StaffAdapter(activity, activity.listContact);
                            activity.mStaffAdapter.notifyDataSetChanged();
                            activity.listView.setAdapter(activity.mStaffAdapter);
                            activity.pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        }else {
                            Toast.makeText(activity, "暂时没有数据", Toast.LENGTH_SHORT).show();
                            activity.pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                        break;

                }
            }
        }
    }
    private final MyHandler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staff);
        staffActivity = this;
        initViews();
        if(Tools.isNetworkAvailable(this)){
            getContacts(1,getIntent().getStringExtra("fid"), load);
        }else {
            Toast.makeText(this, "当前没有可用的网络", Toast.LENGTH_SHORT).show();
        }

//        initAdapter();

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        cbSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cbSearch.isChecked()){
                    llSearch.setVisibility(View.VISIBLE);
                }else {
                    llSearch.setVisibility(View.GONE);
                }
            }
        });

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(tvSearch);
            }
        });

        btnFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Tools.isNetworkAvailable(StaffActivity.this)){
                    --page;
                    if (page >= 1){
                        tvPage.setText("当前第"+page+"页");
                        getContacts(page,getIntent().getStringExtra("fid"), pull_up);

                    }else {
                        Toast.makeText(StaffActivity.this, "当前已是第一页", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(StaffActivity.this, "当前没有可用的网络", Toast.LENGTH_SHORT).show();
                }

            }
        });

        btnBehind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Tools.isNetworkAvailable(StaffActivity.this)){
                    ++page;
                    tvPage.setText("当前第"+page+"页");
                    getContacts(page,getIntent().getStringExtra("fid"), pull_down);
                }else {
                    Toast.makeText(StaffActivity.this, "当前没有可用的网络", Toast.LENGTH_SHORT).show();
                }
            }
        });



//        initListView();


    }

    private void initViews(){
        btnBack = (Button)findViewById(R.id.btnBack);
        cbSearch = (CheckBox)findViewById(R.id.cbSearch);
        llSearch = (LinearLayout)findViewById(R.id.llSearch);
        tvSearch = (TextView)findViewById(R.id.tvSearch);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        lvStaff = (ListView)findViewById(R.id.lvStaff);
        btnFront = (Button)findViewById(R.id.btnFront);
        btnBehind = (Button)findViewById(R.id.btnBehind);
        tvPage = (TextView) findViewById(R.id.tvPage);
        tvPage.setText("当前第"+page+"页");

//        ((PullToRefreshLayout) findViewById(R.id.refresh_view))
//                .setOnRefreshListener(new MyListener());
//        PullToRefreshLayout pullToRefreshLayout = new PullToRefreshLayout(staffActivity);
        pullToRefreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
//        pullToRefreshLayout.setOnRefreshListener(new MyListener());
        pullToRefreshLayout.setOnRefreshListener(this);
        listView = (ListView) findViewById(R.id.content_view);
    }

    public void onRefresh()
    {
        mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);
    }

//    private void initAdapter(){
//        list_staff = new ArrayList<Map<String, String>>();
//        for (int i = 0; i < 10; i++) {
//            Map<String, String> map = new HashMap<String, String>();
//            list_staff.add(map);
//        }
//
//        mStaffAdapter = new StaffAdapter(this, list_staff);
//        lvStaff.setAdapter(mStaffAdapter);
//    }


    /**
     * 显示PopupWindow弹出菜单
     */
    private void showPopupWindow(View parent) {
        if (popWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = layoutInflater.inflate(R.layout.popwindow_search, null);
            dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 创建一个PopuWidow对象
//            popWindow = new PopupWindow(view, dm.widthPixels, LinearLayout.LayoutParams.WRAP_CONTENT);
            popWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            LinearLayout llFuzzy = (LinearLayout)view.findViewById(R.id.llFuzzy);//添加车友
            llFuzzy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    ll_chat.setBackgroundColor(Color.parseColor("#00000000"));
                    tvSearch.setText("模糊查询");
                    popWindow.dismiss();
                }
            });

            LinearLayout llName = (LinearLayout)view.findViewById(R.id.llName);//添加车友
            llName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    ll_chat.setBackgroundColor(Color.parseColor("#00000000"));
                    tvSearch.setText("姓名");
                    popWindow.dismiss();
                }
            });

            LinearLayout llPhone = (LinearLayout)view.findViewById(R.id.llPhone);//添加车友
            llPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    ll_chat.setBackgroundColor(Color.parseColor("#00000000"));
                    tvSearch.setText("手机");
                    popWindow.dismiss();
                }
            });

//
        }

        // 实例化一个ColorDrawable颜色为半透明
//        ColorDrawable dw = new ColorDrawable(0xb0000000);
        Drawable dw = getResources().getDrawable(android.R.color.white);
//        Drawable dw = getResources().getDrawable(R.drawable.navigation);
        popWindow.setBackgroundDrawable(this.getResources().getDrawable(
                R.drawable.bg_pop_list));

        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(false);
        // 设置背景，这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
//        popWindow.setBackgroundDrawable(new BitmapDrawable());
        // PopupWindow的显示及位置设置
        // popWindow.showAtLocation(parent, Gravity.FILL, 0, 0);
        popWindow.showAsDropDown(parent, 0, 30);

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 改变显示的按钮图片为正常状态
//                changeButtonImage();
//                finish();
            }
        });

        // 监听触屏事件
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                // 改变显示的按钮图片为正常状态

//                Toast.makeText(FunctionActivity.this, "点击屏幕", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }


    public void getContacts(final int page, final String id, final int type){
        new Thread(){
            public void run(){

                try {
                    URL url = new URL("http://hr.hrqylm.com/app/hr/Number.aspx?no=" + page + "&key=" + id);
//                    String content = "";
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    // 设置允许输出
                    conn.setDoOutput(true);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    OutputStream os = conn.getOutputStream();
//                    os.write(content.getBytes("UTF-8"));
                    os.close();
                    //服务器返回的响应码
                    if (conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Tools.getTextFromStream(is);
                        System.out.println("---------------------------" + text);
                        Message msg = new Message();
                        msg.what = type;
                        msg.obj = text;
                        mHandler.sendMessage(msg);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }


    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory() // 设置下载的图片是否缓存在内存中
                .cacheOnDisc() // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }


    /**
     * ListView��ʼ������
     */
    private void initListView()
    {
        List<String> items = new ArrayList<String>();
        for (int i = 0; i < 30; i++)
        {
            items.add("������item " + i);
        }
        MyAdapter adapter = new MyAdapter(this, items);
        listView.setAdapter(adapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id)
            {
                Toast.makeText(
                        StaffActivity.this,
                        "LongClick on "
                                + parent.getAdapter().getItemId(position),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id)
            {
                Toast.makeText(StaffActivity.this,
                        " Click on " + parent.getAdapter().getItemId(position),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void getTest(){

    }


//    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout)
    {
//        new Handler()
//        {
//            @Override
//            public void handleMessage(Message msg)
//            {
//                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
//
//            }
//        }.sendEmptyMessageDelayed(0, 3000);

        getContacts(page,getIntent().getStringExtra("fid"), pull_up);

    }

//    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout)
    {
//        new Handler()
//        {
//            @Override
//            public void handleMessage(Message msg)
//            {
//                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
//            }
//        }.sendEmptyMessageDelayed(0, 3000);

        getContacts(++page,getIntent().getStringExtra("fid"), pull_down);

    }




}
